<template>
  <div class="EvaluateTest h-100% w-100% flex">
    <div class="compile h-100% w-40% flex-col flex-shrink-0">
      <JsonForm
        ref="$jsonForm"
        v-model:isRender="isRender"
        label="评估设置确认"
        :schemas="schemas"
        :line="true"
        @options-load="onOptionsLoad"
      />
      <div class="my-btn-group flex-self-0 justify-end">
        <n-button v-if="!evaluationStatus" :color="appStore.buttonColor" @click="handleExecute">
          执行评估
        </n-button>
        <n-button
          v-if="evaluationStatus === 'UNDER_EVALUATION'"
          :color="appStore.buttonColor"
          @click="handleStop"
        >
          终止评估
        </n-button>
        <n-button
          v-if="evaluationStatus === 'TERMINATION_OF_EVALUATION'"
          :color="appStore.buttonColor"
          @click="backHome"
        >
          返回首页
        </n-button>
      </div>
    </div>
    <div
      class="output ml-30 box-border flex-col flex-1 pl-30"
      :style="{
        borderLeft: appStore.isDeep ? '1px solid rgba(43,161,255,0.3)' : '1px solid #e7eaf0',
      }"
    >
      <div class="flex flex-shrink-0 items-center justify-between">
        <div v-if="appStore.isDeep" class="deep-label">评估输出</div>
        <div v-else class="color-140D35 text-28">评估输出</div>
        <div
          v-if="evaluationStatus"
          class="flex items-center gap-6 text-14"
          :style="{ color: statusResult.color }"
        >
          <img class="my-loading h-16 w-16" :src="appStore.isDeep ? deepLoading : lightLoading" />

          {{ statusResult.text }}
        </div>
      </div>
      <div class="my-card mt-16 flex-1">
        <n-scrollbar ref="$output">
          <div v-for="(item, index) in outputList" :key="index">
            {{ item }}
          </div>
        </n-scrollbar>
      </div>
    </div>
  </div>
</template>
<script setup lang="jsx">
import { useAppStore } from '@/store'
import { useMqttStore } from '@/store'
import * as testRecordApi from '@/api/testRecord'
import * as testObjectApi from '@/api/testObject'
import * as evaluateRecordApi from '@/api/evaluateRecord'
import lightLoading from '@/assets/images/light-loading.png'
import deepLoading from '@/assets/images/deep-loading.png'
import { computed } from 'vue'
defineOptions({
  name: 'EvaluateTest',
})
const appStore = useAppStore()
const emits = defineEmits(['next', 'prev', 'report'])
const props = defineProps({
  id: {
    type: String,
    default: null,
  },
})

const $jsonForm = ref(null)
const isRender = ref(false)
function getTaskActionList() {
  return evaluateRecordApi.actionList()
}
function getEvaluateIndicatorList() {
  return testObjectApi.evaluateIndicator()
}
function getEvaluationModelList() {
  return testObjectApi.evaluationModelList({ testRecordId: props.id })
}

const schemas = computed(() => {
  return [
    {
      field: 'evaluationAction',
      label: '评估任务操作类型',
      component: 'AsyncSelect',
      rule: [{ required: true, message: '请选择评估任务操作类型' }],
      componentProps: {
        defaultValue: null,
        options: getTaskActionList,
        labelKey: 'name',
        valueKey: 'code',
        disabled: executeId.value,
      },
      enableFormat: 'async',
    },
    {
      field: 'evaluationIndicatorIdList',
      label: '评估指标',
      component: 'MyTags',
      rule: [{ required: true, message: '请选择评估指标' }],
      componentProps: {
        defaultValue: [],
        options: getEvaluateIndicatorList,
        labelKey: 'estimateIndicatorName',
        valueKey: 'id',
        multiple: true,
        disabled: executeId.value,
      },
      enableFormat: 'async',
    },

    {
      field: 'evaluationModel',
      label: '评估模型',
      component: 'AsyncSelect',
      rule: [{ required: true, message: '请选择评估模型' }],
      componentProps: {
        defaultValue: null,
        options: getEvaluationModelList,
        labelKey: 'name',
        valueKey: 'id',
        disabled: executeId.value,
        onUpdateValue(_, item) {
          $jsonForm.value.setFormData({ evaluationModelPara: JSON.stringify(item?.paraList || []) })
        },
      },
      enableFormat: 'async',
    },
    {
      field: 'evaluationModelPara',
      label: '评估模型参数',
      component: 'NInput',
      rule: [{ required: true, message: '请选择评估模型参数' }],
      componentProps: {
        defaultValue: null,
        type: 'textarea',
        autosize: {
          minRows: 3,
        },
        disabled: executeId.value,
      },
    },
    // {
    //   field: 'scenarioInfo',
    //   label: '场景信息',
    //   component: 'NInput',
    //   rule: [{ required: true, message: '请选择场景信息' }],
    //   componentProps: {
    //     defaultValue: null,
    //     type: 'textarea',
    //     autosize: {
    //       minRows: 3,
    //     },
    //     disabled: executeId.value,
    //   },
    // },
    // {
    //   field: 'actionParas',
    //   label: '操作类型参数',
    //   component: 'NInput',
    //   rule: [{ required: true, message: '请选择操作类型参数' }],
    //   componentProps: {
    //     defaultValue: null,
    //     type: 'textarea',
    //     autosize: {
    //       minRows: 3,
    //     },
    //     disabled: executeId.value,
    //   },
    // },
    // {
    //   field: 'extra',
    //   label: '其他信息',
    //   component: 'NInput',
    //   rule: [{ required: true, message: '请选择其他信息' }],
    //   componentProps: {
    //     defaultValue: null,
    //     type: 'textarea',
    //     autosize: {
    //       minRows: 3,
    //     },
    //     disabled: executeId.value,
    //   },
    // },
  ]
})
const name = ref('')
async function getInfo() {
  const {
    data: {
      evaluationIndicatorCollection,
      evaluationMode,
      testObjectTypeName,
      tagName,
      evaluationModeParameters,
    },
  } = await testRecordApi.info(props.id)
  $jsonForm.value.setFormData({
    evaluationIndicatorIdList: evaluationIndicatorCollection?.length
      ? evaluationIndicatorCollection.split(',')
      : [],
    evaluationModel: evaluationMode,
    evaluationModelPara: evaluationModeParameters,
  })
  name.value = `${testObjectTypeName}-${tagName}-${Date.now()}-评估`
}
function onOptionsLoad() {
  nextTick(() => {
    getInfo()
  })
}

const $output = ref(null)
const outputList = ref([])
const executeId = ref(null)
const currentTopic = computed(() => `eval-${executeId.value}`)
let timer = null
const mqttStore = useMqttStore()
function handleExecute() {
  $jsonForm?.value?.validateForm((data, json) => {
    evaluateRecordApi
      .execute({
        ...data,
        testRecordId: props.id,
        name: name.value,
        evaluationModel: json.evaluationModel,
      })
      .then((res) => {
        $message.success('执行评估成功!')
        executeId.value = res.data.id
        timer = setInterval(() => {
          getStatus()
        }, 1000)
        mqttStore.subscribe({
          topic: currentTopic.value,
          callback(_, msg) {
            outputList.value.push(msg)
            nextTick(() => {
              $output.value.scrollTo({ top: 1000 })
            })
          },
        })
      })
  })
}

onBeforeUnmount(() => {
  mqttStore.unsubscribe(currentTopic.value)
  clearInterval(timer)
  timer = null
})

const lightStatusMap = {
  UNDER_EVALUATION: {
    text: '评估中',
    color: '#2F54EB',
  }, // 评估中
  TERMINATION_OF_EVALUATION: {
    text: '评估终止',
    color: '#F74732',
  }, //评估终止
  EVALUATION_COMPLETE: {
    text: '评估完成',
    color: '#34AA44',
  }, //评估完成
}
const deepStatusMap = {
  UNDER_EVALUATION: {
    text: '评估中',
    color: '#4AC8FF',
  }, // 评估中
  TERMINATION_OF_EVALUATION: {
    text: '评估终止',
    color: '#F74732',
  }, //评估终止
  EVALUATION_COMPLETE: {
    text: '评估完成',
    color: '#34AA44',
  }, //评估完成
}
const statusResult = computed(() =>
  evaluationStatus.value
    ? (appStore.isDeep ? deepStatusMap : lightStatusMap)[evaluationStatus.value]
    : {}
)
const evaluationStatus = ref(null)
function getStatus() {
  evaluateRecordApi
    .info({ id: executeId.value })
    .then(({ data }) => {
      evaluationStatus.value = data.evaluationStatus
      if (data.evaluationStatus != 'UNDER_EVALUATION') {
        clearInterval(timer)
        timer = null
      }
      if (data.evaluationStatus === 'EVALUATION_COMPLETE') {
        emits('report', executeId.value)
        emits('next')
      }
    })
    .catch(() => {
      clearInterval(timer)
      timer = null
    })
}
function handleStop() {
  evaluateRecordApi.stop({ id: executeId.value }).then(() => {
    $message.success('终止评估成功!')
  })
}

const router = useRouter()
function backHome() {
  router.replace('/test')
}
</script>
<style lang="scss" scoped>
.my-loading {
  animation: load 1s linear infinite;
}

@keyframes load {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.deep-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 20px;
  color: #4ddef4;
  font-weight: bold;
  &::before {
    content: '';
    display: block;
    width: 30px;
    height: 22px;
    background: url(@/assets/images/deep-title-icon.png);
  }
}
</style>
